<template>
  <ele-modal v-bind="modalConfig(visible, updateVisible, save, loading, title)">
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 4, sm: 5, xs: 24 } : { flex: '90px' }"
    >
      <li v-for="(item, index) in getFormFields()" :key="index">
        <a-row v-if="item.length == 1">
          <a-col :span="24">
            <a-form-item
              :label="item[0].title"
              :label-col="{ md: 2 }"
              :name="item[0].field"
            >
              <a-input-number
                v-if="
                  item[0].fieldType === FieldTypeEnum.InputNumber &&
                  !item[0].formHidden
                "
                style="width: 100%"
                v-model:value="form[item[0].field]"
              />
              <a-select
                v-if="
                  item[0].fieldType === FieldTypeEnum.Select &&
                  !item[0].formHidden
                "
                v-model:value="form[item[0].field]"
                :options="item[0].FkData()"
              />
              <a-input
                v-if="
                  item[0].fieldType === FieldTypeEnum.Input &&
                  !item[0].formHidden
                "
                allow-clear
                v-model:value="form[item[0].field]"
              />
              <a-date-picker
                v-if="
                  item[0].fieldType === FieldTypeEnum.InputDate &&
                  !item[0].formHidden
                "
                style="width: 100%"
                v-model:value="form[item[0].field]"
              />
              <a-textarea
                v-if="
                  item[0].fieldType === FieldTypeEnum.Textarea &&
                  !item[0].formHidden
                "
                allow-clear
                v-model:value="form[item[0].field]"
              />
              <a-radio-group
                v-if="
                  item[0].fieldType === FieldTypeEnum.BooleanRadio &&
                  !item[0].formHidden
                "
                v-model:value="form[item[0].field]"
                button-style="solid"
                :options="item[0].BoolRadioData"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16" v-else>
          <a-col :span="12" v-for="(row, key) in item" :key="key">
            <a-form-item :label="row.title" :name="row.field">
              <a-input-number
                v-if="
                  row.fieldType === FieldTypeEnum.InputNumber && !row.formHidden
                "
                style="width: 100%"
                v-model:value="form[row.field]"
              />
              <a-select
                v-if="row.fieldType === FieldTypeEnum.Select && !row.formHidden"
                v-model:value="form[row.field]"
                :options="row?.FkData()"
              />
              <a-input
                v-if="row.fieldType === FieldTypeEnum.Input && !row.formHidden"
                allow-clear
                v-model:value="form[row.field]"
              />
              <a-date-picker
                v-if="
                  row.fieldType === FieldTypeEnum.InputDate && !row.formHidden
                "
                v-model:value="form[row.field]"
              />
              <a-radio-group
                v-if="
                  row.fieldType === FieldTypeEnum.BooleanRadio &&
                  !row.formHidden
                "
                v-model:value="form[row.field]"
                button-style="solid"
                optionType="button"
                :options="row.BoolRadioData"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </li>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue/es';
  import type { FormInstance, Rule } from 'ant-design-vue/es/form';
  import { storeToRefs } from 'pinia';
  import { useThemeStore } from '@/store/modules/theme';
  import useFormData from '@/utils/use-form-data';
  import { add, update } from '@/api/application/apiConfig';
  import { ApiConfigList } from '@/api/application/apiConfig/model';
  import { modalConfig } from '@/utils';
  import { computed } from 'vue';
  import { useConfig } from '../config';
  import { FieldTypeEnum } from '@/api/enum';

  const { getFormFields } = useConfig();
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: ApiConfigList | null;
  }>();

  //
  const formRef = ref<FormInstance | null>(null);

  // 是否是修改
  const isUpdate = ref(false);

  const title = computed(() => (isUpdate.value ? '编辑' : '添加'));
  // 提交状态
  const loading = ref(false);

  // 表单数据
  const { form, resetFields } = useFormData<ApiConfigList>({
    id: 0,
    code: '',
    name: '',
    status: 1,
    isMaster: 'N',
    isAudit: 'N',
    isSubmit: 'N'
  });

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    code: [
      {
        required: true,
        message: '请输入编码',
        type: 'string',
        trigger: 'blur'
      }
    ],
    name: [
      {
        required: true,
        message: '请输入名称',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const saveOrUpdate = isUpdate.value ? update : add;
        saveOrUpdate(form)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          Object.assign(form, props.data);
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>
